package cn.edu.zjicm.wordsnet_d.view;


import cn.edu.zjicm.wordsnet_d.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

public class RoundProgressBar extends View {

	private Paint paint;
	/**
	 * 圆环进度的颜色
	 */
	private int roundProgressColor;
	/**
	 * 圆环的宽度
	 */
	private float roundWidth;
	private int max;
	private int progress;
	private RectF oval;

	public RoundProgressBar(Context context) {
		this(context, null);
	}

	public RoundProgressBar(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public RoundProgressBar(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		paint = new Paint();

		TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBar);

		// 获取自定义属性和默认值
		roundProgressColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundProgressColor, Color.GREEN);
		roundWidth = mTypedArray.getDimension(R.styleable.RoundProgressBar_roundWidth, 5);
		max = mTypedArray.getInteger(R.styleable.RoundProgressBar_max, 100);

		mTypedArray.recycle();
		oval = new RectF();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		int center = getWidth() / 2; // 获取圆心的x坐标
		int radius = (int) (center - roundWidth / 2); // 圆环的半径
		/**
		 * 画圆弧,圆环的进度
		 */
		paint.setStrokeWidth(roundWidth); // 设置圆环的宽度
		paint.setColor(roundProgressColor); // 设置进度的颜色
		paint.setAntiAlias(true);

		oval.set(center - radius, center - radius, center + radius, center + radius);
		paint.setStyle(Style.STROKE);
		canvas.drawArc(oval, -90, 360 * progress / max, false, paint); // 根据进度画圆弧
	}

	public synchronized int getMax() {
		return max;
	}

	public synchronized void setMax(int max) {
		if (max < 0) {
			throw new IllegalArgumentException("max not less than 0");
		}
		this.max = max;
	}

	public synchronized int getProgress() {
		return progress;
	}

	public synchronized void setProgress(int progress) {
		if (progress < 0) {
			throw new IllegalArgumentException("progress not less than 0");
		}
		if (progress > max) {
			progress = max;
		}
		if (progress <= max) {
			this.progress = progress;
			postInvalidate(); // 能在非UI线程刷新
		}

	}

}
